﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using WebDAVSharp.Server.Stores;
using WebDAVSharp.Server.Stores.DiskStore;

namespace AzureStorageLight
{
    public class AppWebDavStoreDocument : AppWebDavStoreItem, IWebDavStoreDocument
    {
        public AppWebDavStoreDocument(AppWebDavStoreCollection parentCollection, string path)
            : base(parentCollection, path)
        {
        }

        public string Etag
        {
            get
            {
                return StorageItemUtil.Md5HashStringForUtf8String(ItemPath + ModificationDate + Hidden + Size);
            }
        }

        public string MimeType
        {
            get
            {
                return "*/application";
            }
        }

        public long Size
        {
            get
            {
                return Item.Size;
            }
        }

        public override DateTime ModificationDate
        {
            get
            {
                return Item.LastModified;
            }
        }


        public Stream OpenReadStream()
        {
            var st = new MemoryStream();
            var temp = Path.GetTempFileName();
            try
            {
                Service.DownloadAsync(ItemPath, temp).Wait();
                using (var fs = new FileStream(temp, FileMode.Open))
                {
                    fs.CopyTo(st);
                }
            }
            finally
            {
                File.Delete(temp);
            }
            st.Seek(0, SeekOrigin.Begin);
            return st;

        }

        class MyMemoryStream : MemoryStream
        {
            Action<MemoryStream> callback;
            public MyMemoryStream(Action<MemoryStream> callback)
            {
                this.callback = callback;
            }
            public override void Close()
            {
                this.Seek(0, SeekOrigin.Begin);
                callback(this);
                base.Close();

            }
        }

        public Stream OpenWriteStream(bool append)
        {
            if (append)
            {
                throw new NotSupportedException();
            }

            var st = new MyMemoryStream((x) =>
            {
                var temp = Path.GetTempFileName();
                try
                {
                    using (var fs = new FileStream(temp, FileMode.Create))
                    {
                        x.CopyTo(fs);
                    }
                    Service.UploadAsync(ItemPath, temp).Wait();
                }
                finally
                {
                    File.Delete(temp);
                }
            });
            return st;
        }
    }
}